import * as THREE from '../../build/three.module.js';
import {
  OrbitControls
} from '../../jsm/controls/OrbitControls.js'

const scene = new THREE.Scene();

/**
 * 通过 TextureLoader.load() 加载一个图片，返回纹理对象，设置成 材质对象 .map 属性，将纹理应用到几何体上
 */
// 要将纹理映射到矩形平面上
const geoPlane = new THREE.PlaneGeometry(256, 256);
// 将纹理投影在圆上
const geoCir = new THREE.SphereGeometry(100, 32, 32);
// 将纹理映射在立方体
const geoBox = new THREE.BoxGeometry(200, 200, 200);
// TextureLoader 创建一个纹理家载器
const textureLoader = new THREE.TextureLoader();
// 执行 .load 方法，加载纹理贴图
textureLoader.load('../../textures/metal.jpg', texture => {
  console.log(texture);
  const mat = new THREE.MeshLambertMaterial({
    side: THREE.DoubleSide,
    map: texture // 将纹理对象设置为颜色纹理贴图属性 .map
  });
  const meshPlane = new THREE.Mesh(geoPlane, mat);
  scene.add(meshPlane);

  const meshShpere = new THREE.Mesh(geoCir, mat);
  meshShpere.translateX(-300);
  scene.add(meshShpere);

  const meshBox = new THREE.Mesh(geoBox, mat);
  meshBox.translateX(300);
  scene.add(meshBox);

  render();
});
/**
 * 通过图片加载器 ImageLoader 也可以加载一张图片，并通过纹理类 Texture 实例化一个纹理对象
 * 此时 Texture 实例对象的 .image 属性就是加载的这张图片
 */
const imageLoader = new THREE.ImageLoader();
imageLoader.load('../../textures/metal.jpg', img => {
  // 创建纹理对象
  const texture = new THREE.Texture(img);
  // 显式设置材质对象变化时重新编译材质
  texture.needsUpdate = true;
  const mat = new THREE.MeshLambertMaterial({
    map: texture
  });
  console.log(mat);
  // 也实现了纹理对象的构建
});

const al = new THREE.AmbientLight(0xffffff); // 打上环境光，否则纹理是黑的
scene.add(al);

const acesH = new THREE.AxesHelper(200);
scene.add(acesH);

const k = innerWidth / innerHeight,
      s = 400,
      camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
camera.position.set(0, 0, 400);
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xeeeeee);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
new OrbitControls(camera, renderer.domElement);

// (function render() {
//   requestAnimationFrame(render);
//   renderer.render(scene, camera);
// })();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}